$(function(){
	$.getJSON('json/min/china.json',function(data){
		 echarts.registerMap('china', data);
		 var chart = echarts.init(document.getElementById('map'));
		 var option = {
		 	title:{
		 		show:true,
		 		text:'中国',
		 		textAlign:'center',
		 		left:'center',
		 		textStyle:{
		 			color:'#888'
		 		}
		 	},
		    tooltip: {
		        trigger: 'item',
		        enterable:true,
		        backgroundColor:'rgba(255,255,255,0)',
		        formatter:function(params,ticket,callback){
		        		var res = "<div style='width:300px;height:200px'>";
		        		res+="<img src='img/tooltip.png' width='100%' height='100%'>";
		        		res +="</div>";
		        		return res;
		        }
		    },
		    series: [
		        {
		            type: 'map',
		            mapType: 'china',
		            roam:'scale',//开启鼠标缩放和平移漫游
		            selectedMode : 'single',
		            label: {
		                normal: {
		                    show: true
		                },
		                emphasis: {
		                    show: true
		                }
		            },
		            itemStyle:{
		            		normal:{
		            			borderWidth:1,
		            			borderColor:'#FFF',
		            			areaColor:'#91CA79',
		            			label:{
		            				show:true,
		            				textStyle:{
		            					color:'#888'
		            				}
		            			}
		            		},
		            		emphasis:{
		            			borderWidth:1,
		            			borderColor:'#91CA79',
		            			areaColor:'#fff',
		            			label:{
		            				show:true,
		            				textStyle:{
		            					color:'#91CA79'
		            				}
		            			}
		            		}
		            },
		            animation: false,
		            data: [{  
        						name:"南海诸岛",value:0,  
        						itemStyle:{  
            					normal:{opacity:0,label:{show:false}}  
        						}  
      					}]
		        }
		    ]
		};
		chart.setOption(option);
		var curIndex = -1,subIndex = -1;
		chart.on('mapselectchanged',function(params){
			var series = params.batch[0].name;
			if(curIndex==-1){
				//选择省
				$.each(mapType,function(index){
					if(this.name == series){
						curIndex = index;
						return false;
					}
				});
				$('#back').text('显示完整地图');
				$('#back').show();
			}else if(subIndex==-1){
				//选择市
				$.each(mapType[curIndex].cities,function(index){
					if(this.name == series){
						subIndex = index;
						return false;
					}
				});
				//没有市
				if(subIndex == -1){
					//回到china
					curIndex = -1;
					$('#back').text('显示完整地图');
					$('#back').show();
					getBoundary(series);
				}else{
					$('#back').text('显示'+mapType[curIndex].name);
					$('#back').show();
				}
			}else{
				//选择县／区
				curIndex = -1;
				subIndex = -1;
				getBoundary(series);
			}
			//进入省
			if(curIndex != -1){
				var url = mapType[curIndex].url,name=mapType[curIndex].name,loadFlag=mapType[curIndex].flag,type = 1;
				//进入市
				if(subIndex != -1 && mapType[curIndex].cities.length>0){
					url = mapType[curIndex].cities[subIndex].url;
					name = mapType[curIndex].cities[subIndex].name;
					loadFlag = mapType[curIndex].cities[subIndex].flag;
					getBoundary(series);
					type = 2;
				}
				option.title.text = name;
				if(!loadFlag){
					$.getJSON(url,function(data){
						console.log(data);
						if(type == 1){
							mapType[curIndex].flag = true;
						}else if(type==2){
							mapType[curIndex].cities[subIndex].flag = true;
						}
						echarts.registerMap(name, data);
						option.series[0].mapType = series;
						chart.setOption(option);
				    });
				}else{
					option.series[0].mapType = series;
				    chart.setOption(option);
				}
			}else{
				//没有进入省，回到china
				option.title.text = '中国';
				option.series[0].mapType = 'china';
				chart.setOption(option);
				$('#back').hide();
			}
			
		});
		chart.on('mouseover',function(params){
		});
		$('#back').on('click',function(){
			if(subIndex!=-1){
				subIndex = -1;
				option.series[0].mapType = mapType[curIndex].name;
				option.title.text = mapType[curIndex].name;
				$('#back').text('显示完整地图');
			}else{
				curIndex = -1;
				option.title.text='中国';
				option.series[0].mapType = 'china';
				$('#back').hide();
			}
			bmap.centerAndZoom(new BMap.Point(116.404,39.915),10);
			BMapLib.AreaRestriction.clearBounds();//清理边界限制
			chart.setOption(option);
		});
	});
	var bmap = new BMap.Map('bmap'),
	point = new BMap.Point(116.404, 39.915),
	width = $('#bmap').width(),
	height = $('#bmap').height();
	bmap.centerAndZoom(point,8);
	//启用滚轮放大缩小
	bmap.enableScrollWheelZoom();
	
	bmap.addEventListener('mousemove',function(e){
		$('.tooltip').remove();
		var pixel = e.pixel;
		var html = '<div class="tooltip"><img src="img/tooltip.png" /></div>';
		var $tooltip = $(html).appendTo($('#bmap'));
		var css;
		if(pixel.x + 300 >= width){
			css = {
				right:width - pixel.x + 10,
			};
			if(pixel.y + 150 >= height){
				css.bottom = height - pixel.y + 10;
			}else{
				css.top = pixel.y + 5 ;
			}
		}else{
			css = {
				left:pixel.x + 5
			};
			if(pixel.y + 150 >= height){
				css.bottom = height - pixel.y + 10;
			}else{
				css.top = pixel.y + 5 ;
			}
		}
		$tooltip.css(css);
	});
	
	$('#bmap').on('mouseout',function(){
		$('.tooltip').remove();
	});
	bmap.addEventListener('tilesloaded',function(){
		$('.BMap_cpyCtrl').hide();
		$('.anchorBL').hide();
	});
	//设置行政区域，限制边界
	function getBoundary(city){
		var boundary = new BMap.Boundary();
		boundary.get(city,function(result){
			bmap.clearOverlays();
			var count = result.boundaries.length;
			var leftBottom = {lng:181,lat:91},rightTop = {lng:-181,lat:-91};
			for(var i=0;i<count;i++){
				var positions = result.boundaries[i];
				var polygon = new BMap.Polygon(positions,{strokeWeight:3,strokeColor:'#ffff00',fillColor:'none'});//建立过变形覆盖物
				var path =polygon.getPath();
				bmap.addOverlay(polygon);
				for(var j=0,len=path.length;j<len;j++){
					if(path[j].lng<=leftBottom.lng){
						leftBottom.lng = path[j].lng;
					}
					if(path[j].lat<=leftBottom.lat){
						leftBottom.lat = path[j].lat;
					}
					if(path[j].lng>=rightTop.lng){
						rightTop.lng = path[j].lng;
					}
					if(path[j].lat>=rightTop.lat){
						rightTop.lat = path[j].lat;
					}
				}
				bmap.setViewport(path);
			}
			// 设置边界限制
			var bounds = new BMap.Bounds(leftBottom,rightTop),
			centerLng = (leftBottom.lng+rightTop.lng) / 2 ,
			centerLat = (leftBottom.lat + rightTop.lat) / 2;
			BMapLib.AreaRestriction.setBounds(bmap,bounds);
			bmap.centerAndZoom(new BMap.Point(centerLng,centerLat),8);
		});
	}
});
